/**
 * 自定义认证
 */
Ext.apply(Ext.form.VTypes, {
	subjectfield: function(val, field){
		var result = /[^a-zA-Z0-9_@#]/.test(val);
		return !result;
	},
    subjectfieldText: '字段ID只能含有英文字母(a-Z)、数字(0~9)、下划线(_,@,#)'
});
/**
 * 
 * @class TemplatePanel
 * @extends Ext.FormPanel
 */
TemplatePanel = Ext.extend(Ext.FormPanel,{
	tmplGridPnl: null,
	constructor: function(config){
		Ext.apply(this,config);
		
		this.tmplGridPnl = new TemplateGridPanel();

		TemplatePanel.superclass.constructor.call(this, {
			region: 'west',
			split: true,
			border: false,
			width: 240,
			title: "表单样式列表",
			iconCls: 'tool_box',
			minSize: 160,
			maxSize: 420,
			border: true,
			collapsible: true,
			collapseMode: 'mini',
			margins: '0 0 0 0',
			cmargins: '0 0 0 0',		
			layout: "fit",
			defaults: {autoScroll:true},
			layoutConfig: {
				titleCollapse: true,
				animate: true
			},
			items: [this.tmplGridPnl]
		});
	}
});
/**
 * 
 * @class TemplateGridPanel
 * @extends Ext.grid.GridPanel
 */
TemplateGridPanel = Ext.extend(Ext.grid.GridPanel,{
	condition: {},
	store: null,
	cm: null,
	searchField: null,
	tmplWin: null,
	constructor: function(config){
		Ext.apply(this,config);
		
		this.condition.limit = 50;
		
		this.store = new Ext.data.Store({
		    baseParams: this.condition,   
			proxy: new Ext.data.HttpProxy({
				method: 'POST',
				url: window.basePath + '/template.htm?method=list'
			}),
			reader: new Ext.data.JsonReader({
				totalProperty: 'totalProperty',
				root: 'root',
				id: 'tmpl_id'
			},[
				{name: 'tmpl_id'},
				{name: 'tmplName'},
				{name: 'dateOfCreate'},
				{name: 'memo'}
			])
		});
		
		this.cm = new Ext.grid.ColumnModel([
	        {
				header: "文件名称",
				dataIndex: 'tmplName',
				sortable: true,
				width: 180
	        },{
				header: "备注",
				dataIndex: 'memo',
				sortable: true,
				width: 70
	        }]);
        	        
		this.searchField = new Ext.ux.form.SearchField({store: this.store, width:100});
		
		TemplateGridPanel.superclass.constructor.call(this, {
			id: 'tmplGridPnl',
		    loadMask: {msg: '数据载入中...'},
		    viewConfig: {
		    	forceFit: true
		    },
		    stripeRows: true,
		    //columnLines: true,
			region: 'center',
			border: false,
			height: 500,
			layout: 'fit',
			split: true,
			cls: 'x-rb',
			ds: this.store,
			sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
			cm: this.cm,
			trackMouseOver: false,
			tbar: [{
				text: "选项",
				scope: this,
				tooltip: "对表单模板列表进行新增、修改、删除、操作",
				menu: {
					items: [{
						text: "新增",
						iconCls: 'add',
						scope: this,
						handler: function(){
							if(Ext.isEmpty(this.tmplWin)) this.tmplWin = new TemplateWindow();
							else this.tmplWin.reset();
							this.tmplWin.show();
						}
					},{
						text: "编辑",
						iconCls: 'edit',
						scope: this,
						handler: function(){
							var record = this.getSelectionModel().getSelected();
							
							if(Ext.isEmpty(record)) Ext.Msg.alert("温馨提示：","请选择要编辑的模板！")
							else
							{
								if(Ext.isEmpty(this.tmplWin)) this.tmplWin = new TemplateWindow();
								else this.tmplWin.reset();
								
								var params = {};
								params.tmpl_id = record.get("tmpl_id");
								params.tmplName = record.get("tmplName");
								params.memo = record.get("memo");
								
								this.tmplWin.setValues(params)
								this.tmplWin.show();
							}
						}
					},{
						text: "删除",
						iconCls: 'delete',
						scope: this,
						handler: function(){
							//var gridPnl = Ext.getCmp("tmplGridPnl");
							var record = this.getSelectionModel().getSelected();
							if(typeof(record) != "undefined"){
								Ext.MessageBox.show({
									title: "温馨提示：",
									msg: "您确认要删除模板["+record.get("tmplName")+"]？",
									buttons: Ext.MessageBox.YESNO,
									fn: function(btn){
										if(btn == "yes")
										{
											Ext.Ajax.request({
												url: '/pdm/category/removeTemplate.htm',
												method: 'post',
												params: {
													tmpl_id: record.get("tmpl_id")
												},
												success: function(response,options){
													var result = Ext.decode(response.responseText).message;
													Ext.Msg.alert("信息:", result);

													var tmplGridPnl = Ext.getCmp("tmplGridPnl");
													tmplGridPnl.load();
												},
												failure: function(response){
													
												}
											});
										}
										else return;
									}
								});
							}else{
								Ext.Msg.alert("温馨提示：","请选择要编辑的模板！")
							}
						}
					}]
				}
			},"-","查询：",this.searchField],
			bbar: new Ext.PagingToolbar({
				pageSize: 50,
				store: this.store,
				displayInfo: true
			})
		});
		this.getSelectionModel().on('rowselect', function(sm, rowIdx, r) {
			var tmpl_id = r.get("tmpl_id");
			document.getElementById("_selected_tmpl_id").value = tmpl_id;
			
			var tmplUsedAttrList = Ext.getCmp("tmplUsedAttrList");
			
			tmplUsedAttrList.setTitle(r.get("tmplName")+"页面元素列表");
			var usedAttrGrid = Ext.getCmp("usedAttrGrid");
			
			usedAttrGrid.reload(tmpl_id);
			
			var attributeInfo = Ext.getCmp("attributeInfo");
			attributeInfo.form.reset();
			
		});
	},
	load: function(){
		this.store.load();
	}
});
	
/****************************************************
 * @class UsedAttrsGrid
 * @extends Ext.grid.EditorGridPanel
 ***************************************************/
	UsedAttrsGrid = Ext.extend(Ext.grid.EditorGridPanel,{
		cm: null,
		store: null,
		condition: null,
		checkColumn: null,
		copyFromTmplWin: null,
		constructor: function(config){
			Ext.apply(this,config);
			
			var addAttributeWindow;
			
			this.checkColumn = new Ext.grid.CheckColumn({
									//header: 'delete?',
									dataIndex: 'del',
									width: 15
								});
			function renderDataType(value) {
				
				if(value=="文本框"||value=="文本框(带备注)"){
					value = '<img src="'+window.basePath+'/images/pdm/textfield.png"/>'+value;
				}
				else if(value=="选择按钮"){
					value = '<img src="'+window.basePath+'/images/pdm/ui-check-box.png"/>'+value;
				}
				else if(value=="单选按钮组"){
					value = '<img src="'+window.basePath+'/images/pdm/ui-radio-button.png"/>'+value;
				}
				else if(value=="日期"){
					value = '<img src="'+window.basePath+'/images/pdm/calendar-day.png"/>'+value;
				}
				else if(value=="整数"){
					value = '<img src="'+window.basePath+'/images/pdm/sort-number.png"/>'+value;
				}
				else if(value=="单行标签"){
					value = '<img src="'+window.basePath+'/images/pdm/tag-label.png"/>'+value;
				}
				else if(value=="标签组"){
					value = '<img src="'+window.basePath+'/images/pdm/tags-label.png"/>'+value;
				}
				else if(value=="文本区域"){
					value = '<img src="'+window.basePath+'/images/pdm/ui-scroll-pane-text.png"/>'+value;
				}
				else if(value=="附件模块"){
					value = '<img src="'+window.basePath+'/images/pdm/attach.png"/>'+value;
				}
				else if(value=="DCC模块"){
					value = '<img src="'+window.basePath+'/images/pdm/folder_open_document.png"/>'+value;
				}
				else if(value=="结论模块(可行、不可行...)"||value=="结论模块(Pass,Fail...)"){
					value = '<img src="'+window.basePath+'/images/pdm/auction_hammer_gavel.png"/>'+value;
				}
				return value;
			}
			
			function renderGroup(value) {
				if(value == "0"){
					value = '无分组';
				}
				return value;
			}
			this.cm = new Ext.grid.ColumnModel([
				new Ext.grid.RowNumberer(),
				this.checkColumn,
				{header:"元素字段",dataIndex:"attr_name", width: 50, sortable: true},
				{header:"标签名称",dataIndex:"label_text", width: 50},
				{header:"排列序号",dataIndex:"sort_order", width: 40, sortable: true},
				{header:"显示方式",dataIndex:"data_type", width: 40 ,renderer: renderDataType},
				{header:"组列序号",dataIndex:"group_number", width: 40, renderer: renderGroup, sortable: true},
				{header:"显示列宽",dataIndex:"col_span", width: 40}
			]);
			
			this.condition = {tmpl_id: 0};
			
			this.store = new Ext.data.Store({
				autoLoad: true,
			    baseParams: this.condition, 
			    proxy: new Ext.data.HttpProxy({
			    	method: 'POST',
					url: '/pdm/sheet/getTemplateAttributes.htm'
				}),
		        reader: new Ext.data.JsonReader({
					 totalProperty: 'totalProperty',
					 root: 'root',
					 id: 'attr_id'
				},[
					{name: 'attr_id'},
					{name: 'attr_name'},
					{name: 'del'},
					{name: 'label_text'},
					{name: 'sort_order'},
					{name: 'data_type'},
					{name: 'data_type_id'},
					{name: 'group_number'},
					{name: 'col_span'},
					{name: 'max_length'},
					{name: 'default_value'},
					{name: 'reference_attr'},
					{name: 'reference_attr_id'}
				])
			});
			
			UsedAttrsGrid.superclass.constructor.call(this, {
				id: 'usedAttrGrid',
				region: 'center',
				//width: 850,
				//autoHeight: true,
				split: true,
				stripeRows: true,
				loadMask: true,
				border: false,
				autoScroll: false,
				cls: 'x-rb',
				viewConfig: {forceFit: true},
				ds: this.store,
				sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
				cm: this.cm,
				plugins: this.checkColumn,
				clicksToEdit: 2,
				tbar:[{
					text: "新增",
					iconCls: 'add',
					handler: function(){
						
						var tmpl_id = Ext.fly("_selected_tmpl_id").dom.value;
						if(tmpl_id=="") {
							alert("no template selected!");
						}else{
							if(!this.addAttributeWindow){
								this.addAttributeWindow = new AddAttributeWindow();
							}
							this.addAttributeWindow.reset();
							this.addAttributeWindow.setTmplId(tmpl_id);
							
							jsonrpc = new JSONRpcClient("/pdm/JSON-RPC");
							try{
								var info = jsonrpc.jabsorbService.getAttributeSize(tmpl_id);
							}catch(e){
								alert(e);
							}
							var jsonInfo = eval("("+info+")");
							this.addAttributeWindow.setValue(jsonInfo);
							this.addAttributeWindow.show();
						}
					}
				},'-',{
					text: "删除",
					iconCls: 'delete',
					handler: function(){
						var usedAttrsGrid = Ext.getCmp("usedAttrGrid");
						var delList = "";
						var m = usedAttrsGrid.store.getModifiedRecords();
						for (var i = 0; i < m.length; i++){
							if(m[i].data['del']){
								delList = delList + m[i].data['attr_id']+","
							}
						}
						if(delList!= ""){
							Ext.MessageBox.show({
								title: "温馨提示：",
								msg: "您确认要删除勾选的页面元素？",
								buttons: Ext.MessageBox.YESNO,
								fn: function(btn){
									if(btn == "yes")
									{
										Ext.Ajax.request({
											url: '/pdm/sheet/removeAttributes.htm',
											method: 'post',
											params: {
												removeList: delList
											},
											success: function(response,options){
												var usedAttrGrid = Ext.getCmp("usedAttrGrid");
												usedAttrGrid.load();
												
												Ext.Msg.alert("信息:","参数已经删除。");
											},
											failure: function(response){
												Ext.Msg.alert("信息:","系统出错，请联系管理员"); 
											}
										});
									}
									else return;
								}
							});
						}
					}
				},"-",{
					text: "从模板复制",
					scope: this,
					tooltip: "从其他表单模板样式中复制！",
					handler: function(){
						var tmpl_id = Ext.fly("_selected_tmpl_id").dom.value;
						if(tmpl_id==""){
							Ext.Msg.alert("温馨提示：","请先选择目标表单模板，再进行拷贝！");
						}else{
							if(!this.copyFromTmplWin){
								this.copyFromTmplWin = new CopyTemplateWindow();
							}
							this.copyFromTmplWin.show();
						}
					}
				},"->",{
					text: "预览",
					iconCls: 'preview',
					tooltip: "预览表单模板样式",
					handler: function(){
						var tmplGridPnl = Ext.getCmp("tmplGridPnl");
						var record = tmplGridPnl.getSelectionModel().getSelected();
						if(Ext.isEmpty(record)) Ext.Msg.alert("提示：","请先选择表单模板，再进行预览！");
						else window.open(window.basePath + "/template.htm?method=preview&tmpl_id=" + record.get("tmpl_id"), "", "height=460px, width=800px, toolbar=no, menubar=no, resizable=yes, scrollbars=yes");
					}
				}]
			});
			
			this.getSelectionModel().on('rowselect', function(sm, rowIdx, r) {
				var attributeInfoPanel = Ext.getCmp('attributeInfo');
				var attr_id = r.get("attr_id");
				var attr_name = r.get("attr_name");
				var label_text = r.get("label_text");
				var sort_order = r.get("sort_order");
				var data_type = r.get("data_type");
				var group_number = r.get("group_number");
				var col_span = r.get("col_span");
				var max_length = r.get("max_length");
				var default_value = r.get("default_value");
				var reference_attr = r.get("reference_attr");
				var reference_attr_id = r.get("reference_attr_id");
				
				attributeInfoPanel.form.reset();
				attributeInfoPanel.form.setValues({
					"attr_id": attr_id,
					"element_id": attr_name,
					"data_type": data_type,
					"row_span": (col_span=="单元格")? "1":"4",
					"label_text": label_text,
					"sort_order": sort_order,
					"group_number": group_number,
					"max_length": max_length,
					"default_value": default_value,
					"reference_attr": reference_attr,
					"ref_attr_id": reference_attr_id
				});
				
				//alert(attr_id+", "+attr_name+", "+label_text+", "+sort_order+", "+data_type+", "+group_number+", "+col_span);
			});
		},
		load: function(){
			this.store.load();
		},
		reload: function(c){
			this.condition.tmpl_id = c;
			this.store.load();
		}
	});	

/****************************************************
 * @class AttributeInfoPanel
 * @extends Ext.FormPanel
 ***************************************************/
	AttributeInfoPanel = Ext.extend(Ext.FormPanel,{
		win_AttributeRef: null,
		constructor: function(config){
			Ext.apply(this,config);

			AttributeInfoPanel.superclass.constructor.call(this, {
				labelAlign: 'right',
				frame: false,
				border: false,
				bodyStyle:'padding:5px',
				width: 600,
				items: [{
				    layout: 'column',
				    border: false,
				    items:[{
				    	columnWidth: 1,
				    	layout: 'form',
				    	hidden: true,
				    	border: false,
				    	items: [{
				        	name: 'attr_id',
				        	xtype: 'textfield',
				        	hidden: true
				        }]
				    },{
				        columnWidth: .5,
				        layout: 'form',
				        border:false,
				        items: [{
				            xtype: 'textfield',
				            vtype: 'subjectfield',
				            fieldLabel: "元素字段",
				            maxLength: 30,
				            allowBlank: false,
				            name: 'element_id',
				            anchor: '95%'
				        },{
				        	xtype: 'iconcombo',
							fieldLabel: "显示方式",
							id: 'icon_diplay_type',
							hiddenName: 'data_type',
							valueField: 'key',
							displayField: 'name',
							editable: false, 
							mode: 'remote',
							allowBlank: true,
							readOnly: false,
							forceSelection: true,
							selectOnFocus: true,
							anchor: '50%',
							iconClsField: 'dataFlag',
							triggerAction: 'all',
							store: new Ext.data.JsonStore({
								url : '/pdm/sheet/getSubDataTypes.htm',
								totalProperty : 'totalProperty',
								root : 'root',
								fields: ['key', 'name', 'dataFlag']
							})
						},{
				        	xtype: 'combo',
				        	fieldLabel: '显示列宽',
							hiddenName: 'row_span',
							valueField: 'key',
							displayField: 'name',
							editable: false, 
							mode: 'local',
							allowBlank: false,
							readOnly: false,
							forceSelection: true,
							selectOnFocus:true,
							anchor: '50%',
							triggerAction: 'all',
							value: '1',
							store: new Ext.data.SimpleStore({
								fields: ['key', 'name'],
								data: ROWSPANS
							})
						},{
				            xtype: 'numberfield',
				            fieldLabel: "最大字数限制",
				            name: 'max_length',
				            anchor: '50%'
				        }]
				    },{
				        columnWidth: .5,
				        layout: 'form',
				        border: false,
				        items: [{
				            xtype: 'textfield',
				            fieldLabel: '标签名称',
				            name: 'label_text',
				            anchor: '95%'
				        },{
				            xtype: 'numberfield',
				            fieldLabel: '显示序号',
				            name: 'sort_order',
				            anchor: '95%'
				        },{
				            xtype: 'numberfield',
				            fieldLabel: '分组序号',
				            name: 'group_number',
				            anchor: '95%'
				        },{
				            xtype: 'textfield',
				            fieldLabel: "默认值",
				            name: 'default_value',
				            anchor: '95%'
				        }]
				    },{
				        columnWidth: .5,
				        layout: 'form',
				        border: false,
				        items: [{
				            xtype: 'textfield',
				            fieldLabel: "数据关联",
				            id: 'reference_attr',
				            name: 'reference_attr',
				            anchor: '95%'
				        }]
				    },{
				        columnWidth: .05,
				        layout: 'form',
				        border: false,
				        items: [{
				            xtype: 'button',
				            text: "设置",
				            tooltip: "选择其他模板中的栏位与此栏位进行关联。",
				            scope: this,
				            handler: function(){
				            	var attr_id = Ext.fly("attr_id").dom.value;
						
								if(attr_id==""){
									Ext.Msg.alert("温馨提示:","请选择页面元素后再进行关联！");
								}else{
			            			if(Ext.isEmpty(this.win_AttributeRef)) this.win_AttributeRef = new AttributeReferenceWindow({id: 'win_AttributeRef'});
			            			this.win_AttributeRef.show();
									this.win_AttributeRef.attributeReferencePanel.load();
								}
				            }
				        }]
				    },{
				        columnWidth: .35,
				        layout: 'form',
				        border: false,
				        items: [{
				            xtype: 'button',
				            text: "重置",
				            tooltip: "清除关联数据。",
				            scope: this,
				            handler: function(){
				            	var attr_id = Ext.fly("attr_id").dom.value;
						
								if(attr_id==""){
									Ext.Msg.alert("温馨提示:","请选择页面元素后再进行重置！");
								}else{
			            			Ext.fly("reference_attr").dom.value = "";
			            			Ext.fly("ref_attr_id").dom.value = "";
								}
				            }
				        }]
				    },{
				        columnWidth: .1,
				        layout: 'form',
				        border: false,
				        items: [{
				            xtype: 'hidden',
				            hiddenLabel: true,
				            id: 'ref_attr_id',
				            name: 'ref_attr_id',
				            hidden: true
				        }]
				    }]
				}],
				tbar:[{
					text: "保存",
					iconCls: 'save',
					scope: this,
					handler: function(){
						var attr_id = Ext.fly("attr_id").dom.value;
						
						if(attr_id==""){
							Ext.Msg.alert("温馨提示:","请选择页面元素后再进行编辑保存！");
						}else{
							this.form.submit({
								url: '/pdm/sheet/editAttributes.htm',
								success: function(form, action)
								{
									var usedAttrGrid = Ext.getCmp("usedAttrGrid");
									usedAttrGrid.load();
								},
								failure: function(form, action) 
								{
									var msg = action.response.responseText;
									var obj = Ext.decode( msg );
									Ext.Msg.alert('温馨提示：', obj.message);
								},
								waitMsg: '正在保存数据，稍后...'
							});
						}
					}
				}]
			});
		}
	});	

/****************************************************
 * @class AddAttributeWindow
 * @extends Ext.Window
 ***************************************************/
	AddAttributeWindow = Ext.extend(Ext.Window,{
		addAttributePanel: null,
		constructor: function(config){
			Ext.apply(this,config);
			
			this.addAttributePanel = new AddAttributePanel();
			
			AddAttributeWindow.superclass.constructor.call(this, {
				id: 'win_AddAttribute',
				layout: 'fit',
				width: 600,
				height: 300,
				modal: true,
				plain: true,
				title: "添加元素",
				iconCls: 'element_add',
				closeAction: 'hide',
				buttonAlign: 'center',
				items: this.addAttributePanel,
				buttons: [{
					text: "保存",
					//iconCls: 'save',
					disabled: false,
					handler: function(){
						var addAttributePanel = Ext.getCmp("addAttributePanel");
						if (addAttributePanel.getForm().isValid()) {
							
							addAttributePanel.form.submit({
								url : '/pdm/sheet/saveAttributes.htm',
								success : function(form, action)
								{
									/*
									var msg = action.response.responseText;
									var obj = Ext.decode( msg );
									Ext.Msg.alert("温馨提示：", obj.message);
									*/
									var addAttributeWin = Ext.getCmp("win_AddAttribute");
									addAttributeWin.hide();
									
									var usedAttrGrid = Ext.getCmp("usedAttrGrid");
									usedAttrGrid.load();
								},
								failure : function(form, action) 
								{
									var msg = action.response.responseText;
									var obj = Ext.decode( msg );
									Ext.Msg.alert("温馨提示：",obj.message);
								},
								waitMsg : '正在保存数据，稍后...'
							});
						}else{
							Ext.Msg.alert('信息', '请确认红色方框里内容是否完整或正确!');
						}
					}
				},{
					text: "取消",
					handler: function(){
						var addAttributeWin = Ext.getCmp("win_AddAttribute");
						addAttributeWin.hide();
					}
				}]
			});
		},
		reset: function()
		{
			this.addAttributePanel.form.reset();
		},
		setValue: function(value)
		{
			this.addAttributePanel.form.setValues({
				"sortOrder": value.sortOrder,
				"groupNumber": value.groupNumber,
				"tmpl_id": value.tmpl_id,
				"maxLength": value.maxLength
			});
		},
		setTmplId: function(tmpl_id){
			this.addAttributePanel.form.setValues({
				"tmpl_id": tmpl_id
			});
		}
	});	

/****************************************************
 * @class AddAttributePanel
 * @extends Ext.FormPanel
 ***************************************************/
	AddAttributePanel = Ext.extend( Ext.FormPanel,{
		displayTypePanel: null,
		constructor: function(config){
			Ext.apply(this,config);
			
			this.displayTypePanel = new DisplayTypePanel();

			AddAttributePanel.superclass.constructor.call(this, {
				id: 'addAttributePanel',
				region: 'center',
				//width: 380,
				//height: 450,
				layout: 'form',
				labelAlign: 'right',
				bodyStyle: 'padding:5px',
				buttonAlign: 'center',
				items: [{
				    layout: 'column',
				    border: false,
				    items:[{
				        columnWidth:.5,
				        layout: 'form',
				        border:false,
				        items: [{
				        	hidden: true,
					    	items: [{
					    		xtype: 'textfield',
					    		name: 'tmpl_id',
						    	value: '3'						    	
					    	}]
					    },{
					    	xtype: 'textfield',
				            vtype: 'subjectfield',
				            fieldLabel: "元素ID",
				            maxLength: 30,
				            name: 'attribute_id',
				            allowBlank: false,
				            anchor: '95%'
				        },{
				            xtype: 'numberfield',
				            fieldLabel: "显示序号",
				            name: 'sortOrder',
				            allowBlank: false,
				            maxValue: 9999,
				            anchor: '95%'
				        },{
				        	xtype:'combo',
				        	fieldLabel: "显示列宽",
							hiddenName: 'rowSpan',
							valueField: 'key',
							displayField: 'name',
							editable: false, 
							mode: 'local',
							allowBlank: false,
							readOnly: false,
							forceSelection: true,
							selectOnFocus:true,
							anchor: '95%',
							triggerAction: 'all',
							value: '1',
							store: new Ext.data.SimpleStore({
								fields: ['key', 'name'],
								data: ROWSPANS
							})
						},{
				            xtype: 'textfield',
				            fieldLabel: "默认值",
				            allowBlank: true,
				            name: 'defaultValue',
				            anchor: '95%'
				        }]
				    },{
				        columnWidth:.5,
				        layout: 'form',
				        border:false,
				        items: [{
				            xtype: 'textfield',
				            fieldLabel: "标签名称",
				            maxLength: 50,
				            allowBlank: false,
				            name: 'labelText',
				            anchor: '95%'
				        },{
				            xtype: 'numberfield',
				            fieldLabel: "分组序号",
				            name: 'groupNumber',
				            maxValue: 100,
				            allowBlank: false,
				            anchor: '95%'
				        },{
				            xtype: 'numberfield',
				            fieldLabel: "最大字数限制",
				            name: 'maxLength',
				            allowBlank: true,
				            anchor: '95%'
				        }]
				    },{
				        columnWidth: 1,
				        layout: 'form',
				        border: false,
				        items: [{
				            xtype: 'tabpanel',
				            enableTabScroll: true,
							activeTab: 0,
							items:[{
								title: "显示方式",
								id: 'tab_display',
								layout: 'fit',
								height: 50,
								items: [this.displayTypePanel]
							}]
				        }]
				    }]
				}]
			});
		}
	});
	
/**
 * 
 * @class DisplayTypePanel
 * @extends Ext.Panel
 */
DisplayTypePanel = Ext.extend(Ext.Panel,{
	constructor: function(config){
		Ext.apply(this,config);

		DisplayTypePanel.superclass.constructor.call(this, {
			labelAlign: 'right',
			//labelWidth: 70,
			frame: false,
			border: false,
			bodyStyle: 'padding:5px',
			//width: 560,
			items: [{
				layout: 'column',
				border: false,
				items:[{
			        columnWidth: 1,
			        layout: 'form',
			        border:false,
			        items: [new Ext.ux.IconCombo({
						fieldLabel: "类型",
						hiddenName: 'data_type',
						valueField: 'key',
						displayField: 'name',
						editable: false, 
						mode: 'remote',
						allowBlank: false,
						readOnly: false,
						forceSelection: true,
						selectOnFocus: true,
						anchor: '95%',
						iconClsField: 'dataFlag',
						triggerAction: 'all',
						store: new Ext.data.JsonStore({
							url : '/pdm/sheet/getSubDataTypes.htm',
							totalProperty : 'totalProperty',
							root : 'root',
							fields: ['key', 'name', 'dataFlag']
						})
					})]
			    }]
		    }]
		});
	}
});
	
/**
 * 
 * @class TemplateWindow
 * @extends Ext.Window
 */
TemplateWindow = Ext.extend(Ext.Window, {
	constructor: function(config){
		Ext.apply(this,config);
		
		TemplateWindow.superclass.constructor.call(this, {
			layout: 'fit',
			width: 360,
			height: 180,
			modal: true,
			closeAction: 'hide',
			plain: true,
			buttonAlign: 'center',
			items: [{
				xtype: 'form',
				region: 'center',
				layout: 'form',
				labelAlign: 'right',
				border: false,
				bodyStyle: 'padding: 5 5 5 5',
				buttonAlign: 'center',
				labelWidth: 60,
				items: [{
					xtype: 'hidden',
		            name: 'tmpl_id',
		            value: ''
		        },{
		            xtype: 'textfield',
		            fieldLabel: "模板名称",
		            maxLength: 100,
		            name: 'templateName',
		            allowBlank: false,
		            anchor: '95%'
		        },{
		            xtype: 'textarea',
		            fieldLabel: "备注",
		            maxLength: 200,
		            name: 'memo',
		            allowBlank: true,
		            anchor: '95%'
		        }]
			}],
			buttons: [{
				text: "保存",
				disabled: false,
				scope: this,
				handler: function(){
					var form = this.findByType('form', false)[0].form;
					if (form.isValid()) {
						form.submit({
							url: window.basePath + '/template.htm?method=input',
							scope: this,
							success: function(form, action)
							{
								this.hide();
								
								var tmplGridPnl = Ext.getCmp("tmplGridPnl");
								tmplGridPnl.load();
							},
							failure: function(form, action) 
							{
								var msg = action.response.responseText;
								var obj = Ext.decode( msg );
								Ext.Msg.alert("异常：", obj.message);
							},
							waitMsg: '正在保存数据，稍后...'
						});
					}
					else Ext.Msg.alert('信息', '请确认红色方框里内容是否完整或正确!');
				}
			},{
				text: "取消",
				scope: this,
				handler: function(){
					this.hide();
				}
			}]
		});
	},
	getForm: function()
	{
		return this.findByType('form', false)[0].form;
	},
	reset: function()
	{
		this.getForm().reset();
	},
	setValues: function(params){
		this.reset();
		this.getForm().setValues({
			"tmpl_id": params.tmpl_id,
			"templateName": params.tmplName,
			"memo": params.memo
		});
	}
});	

/****************************************************
 * @class CopyTemplateWindow
 * @extends Ext.Window
 ***************************************************/
	CopyTemplateWindow = Ext.extend(Ext.Window, {
		templateListPanel: null,
		constructor: function(config){
			Ext.apply(this,config);
			
			this.templateListPanel = new TemplateListPanel();
			
			CopyTemplateWindow.superclass.constructor.call(this, {
				id: 'win_CopyTemplate',
				layout: 'fit',
				width: 360,
				height: 480,
				modal: true,
				title: "选择模板复制",
				closeAction: 'hide',
				plain: true,
				buttonAlign: 'center',
				items: this.templateListPanel,
				buttons: [{
					text: "保存",
					disabled: false,
					scope: this,
					handler: function(){
						var record = this.templateListPanel.getSelectionModel().getSelected();
						if(!record){
							Ext.Msg.alert("提示：","请选择需要复制的表单模板！")
						}else{
							var tmplId = record.get("tmpl_id");
							var target_tmpl_id = Ext.fly("_selected_tmpl_id").dom.value;
							if(tmplId == target_tmpl_id){
								Ext.Msg.alert("提示：","无法从自己复制！");
							}else{
								Ext.Ajax.request({
									url: '/pdm/templateAttribute.htm?method=copy',
									method: 'post',
									params: {
										targetId: target_tmpl_id,
										tmplId: tmplId
									},
									success: function(response,options){
										var usedAttrGrid = Ext.getCmp("usedAttrGrid");
										usedAttrGrid.load();
										
										var win_CopyTemplate = Ext.getCmp("win_CopyTemplate");
										win_CopyTemplate.hide();
									},
									failure: function(response){
										
									}
								});
							}
						}
					}
				},{
					text: "取消",
					scope: this,
					handler: function(){
						this.hide();
					}
				}]
			});
		}
	});	

/****************************************************
 * @class TemplateListPanel
 * @extends Ext.grid.GridPanel
 ***************************************************/
	TemplateListPanel = Ext.extend(Ext.grid.GridPanel,{
		condition: {},
		store: null,
		cm: null,
		searchField: null,
		constructor: function(config){
			Ext.apply(this,config);
			
			this.condition.limit = 50;
			
			this.store = new Ext.data.Store({
				autoLoad: true,
			    baseParams: this.condition,   
				proxy: new Ext.data.HttpProxy({
					method: 'POST',
					url: window.basePath + '/template.htm?method=list'
				}),
				reader: new Ext.data.JsonReader({
					totalProperty: 'totalProperty',
					root: 'root',
					id: 'tmpl_id'
				},[
					{name: 'tmpl_id'},
					{name: 'tmplName'},
					{name: 'dateOfCreate'},
					{name: 'memo'}
				])
			});
			this.cm = new Ext.grid.ColumnModel([
		        {
		           header: "文件名称",
		           dataIndex: 'tmplName',
		           sortable: true,
		           width: 180
		        },{
		           header: "备注",
		           dataIndex: 'memo',
		           sortable: true,
		           width: 70
		        }]);
	        	        
			this.searchField = new Ext.ux.form.SearchField({store: this.store, width:200});
			
			TemplateListPanel.superclass.constructor.call(this, {
				id: 'gp_tmpl_list',
			    loadMask: {msg: 'Loading...'},
			    viewConfig: {forceFit: true},
				region: 'center',
				border: false,
				height: 500,
				layout: 'fit',
				split: true,
				cls: 'x-rb',
				ds: this.store,
				sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
				cm: this.cm,
				trackMouseOver: false,
				tbar: ["查询：",this.searchField],
				bbar: new Ext.PagingToolbar({
					pageSize: 50,
					store: this.store,
					displayInfo: true
				})
			});
			this.on('rowdblclick', function(grid, rowIndex, e) {
				var record = grid.getSelectionModel().getSelected();
				var tmplId = record.get("tmpl_id");
				var target_tmpl_id = Ext.fly("_selected_tmpl_id").dom.value;
				if(tmplId == target_tmpl_id){
					Ext.Msg.alert("提示：","无法从自己复制！");
				}else{
					Ext.MessageBox.show({
						title: "温馨提示：",
						msg: "您确认复制["+record.get("tmplName")+"]的页面模板?",
						buttons: Ext.MessageBox.YESNO,
						fn: function(btn){
							if(btn == "yes")
							{
								Ext.Ajax.request({
									url: '/pdm/templateAttribute.htm?method=copy',
									method: 'post',
									params: {
										targetId: target_tmpl_id,
										tmplId: tmplId
									},
									success: function(response,options){
										var usedAttrGrid = Ext.getCmp("usedAttrGrid");
										usedAttrGrid.load();
										
										var win_CopyTemplate = Ext.getCmp("win_CopyTemplate");
										win_CopyTemplate.hide();
									},
									failure: function(response){
										
									}
								});
							}
							else return;
						}
					});
				}
			});
		},
		load: function(){
			this.store.load();
		}
	});
	
/****************************************************
 * @class AttributeReferenceWindow
 * @extends Ext.Window
 ***************************************************/
	AttributeReferenceWindow = Ext.extend(Ext.Window, {
		attributeReferencePanel: null,
		constructor: function(config){
			Ext.apply(this, config);
			
			this.attributeReferencePanel = new AttributeReferencePanel();
			
			AttributeReferenceWindow.superclass.constructor.call(this, {
				layout: 'fit',
				width: 680,
				height: 482,
				modal: true,
				plain: true,
				closeAction: 'hide',
				buttonAlign: 'center',
				items: [this.attributeReferencePanel],
				buttons: [{
					text: "确定",
					scope: this,
					handler: function(){
						var record = this.attributeReferencePanel.attrsList.getSelectionModel().getSelected();
						if(!record){
							Ext.Msg.alert("提示：","请选择相关联的数据！");
						}else{
							Ext.fly("ref_attr_id").dom.value = record.get("attr_id");
							var r = this.attributeReferencePanel.tmplList.getSelectionModel().getSelected();
							
							Ext.fly("reference_attr").dom.value = r.get("tmplName") + " >> " + record.get("label_text");
							
							this.hide();
						}
					}
				},{
					text: "取消",
					scope: this,
					handler: function(){
						this.hide();
					}
				}]
			});
		}
	});
	
/****************************************************
 * @class AttributeReferencePanel
 * @extends Ext.FormPanel
 ***************************************************/
AttributeReferencePanel = Ext.extend(Ext.FormPanel,{
	tmplList: null,
	attrsList: null,
	constructor: function(config){
		Ext.apply(this,config);
		
		this.tmplList = new TemplateListGrid({id: "gp_templateList"});
		this.attrsList = new UsedAttrsList();
		
		AttributeReferencePanel.superclass.constructor.call(this, {
			frame: false,
			border: false,
			//bodyStyle: 'padding: 2px 2px 2px 2px',
			layout: 'column',
			viewConfig: {forceFit: true},
			items: [{
				columnWidth: 0.40,
				layout: 'fit',
				border: true,
				height: 410,
				items: [this.tmplList]
			},{
				columnWidth: 0.01,
				border: false,
				height: 410,
				layout: 'fit'
			},{
				columnWidth: 0.59,
				height: 410,
				border: true,
				layout: 'fit',
				items: [this.attrsList]
			}]
		});
	},
	load: function(){
		this.tmplList.load();
	}
});

/****************************************************
 * @class TemplateListGrid
 * @extends Ext.grid.GridPanel
 ***************************************************/
	TemplateListGrid = Ext.extend(Ext.grid.GridPanel, {
		condition: null,
		store: null,
		cm: null,
		searchField: null,
		constructor: function(config){
			Ext.apply(this,config);
			
			this.condition = {};
			this.condition.limit = 50;
			
			this.store = new Ext.data.Store({
			    baseParams: this.condition,   
				proxy: new Ext.data.HttpProxy({
					method: 'POST',
					url: '/pdm/category/getTemplateList.htm'
				}),
				reader: new Ext.data.JsonReader({
					totalProperty: 'totalProperty',
					root: 'root',
					id: 'tmpl_id'
				},[
					{name: 'tmpl_id'},
					{name: 'tmplName'},
					{name: 'creator'},
					{name: 'dateOfCreate'},
					{name: 'memo'}
				])
			});
			
			this.cm = new Ext.grid.ColumnModel([
		        {
					header: "文件名称",
					dataIndex: 'tmplName',
					sortable: true,
					width: 180
		        },{
					header: "备注",
					dataIndex: 'memo',
					sortable: true,
					width: 70
		        }]);
	        
			this.searchField = new Ext.ux.form.SearchField({store: this.store});
			
			TemplateListGrid.superclass.constructor.call(this, {
			    loadMask: {msg: "数据载入中..."},
			    viewConfig: {forceFit: true},
			    stripeRows: true,
				region: 'center',
				border: false,
				height: 500,
				layout: 'fit',
				split: true,
				cls: 'x-rb',
				ds: this.store,
				sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
				cm: this.cm,
				trackMouseOver: false,
				tbar: ["查询：",this.searchField],
				bbar: new Ext.PagingToolbar({
					pageSize: 50,
					store: this.store,
					displayInfo: true
				})
			});
			
			this.getSelectionModel().on('rowselect', function(sm, rowIdx, r) {
				var tmpl_id = r.get("tmpl_id");
				var tmpl_name = r.get("tmplName");
				var usedAttrsList = Ext.getCmp("usedAttrsList");
				
				usedAttrsList.setTitle("["+tmpl_name+"]元素列表");
				
				usedAttrsList.reload(tmpl_id);
				
			});
		},
		load: function(){
			this.store.load();
		}
	});

/****************************************************
 * @class UsedAttrsList
 * @extends Ext.grid.GridPanel
 ***************************************************/
	UsedAttrsList = Ext.extend(Ext.grid.GridPanel,{
		cm: null,
		store: null,
		condition: null,
		constructor: function(config){
			Ext.apply(this,config);
			
			this.cm = new Ext.grid.ColumnModel([
				new Ext.grid.RowNumberer(),
				{header:"标签名称",dataIndex:"label_text", width: 50},
				{header:"元素字段",dataIndex:"attr_name", width: 50, sortable: true},
				{header:"显示方式",dataIndex:"data_type", width: 40 }
			]);
			
			this.condition = {tmpl_id: 0};
			
			this.store = new Ext.data.Store({
			    baseParams: this.condition,
			    proxy: new Ext.data.HttpProxy({
			    	method: 'POST',
					url: '/pdm/sheet/getTemplateRefAttributes.htm'
				}),
		        reader: new Ext.data.JsonReader({
					 totalProperty: 'totalProperty',
					 root: 'root',
					 id: 'attr_id'
				},[
					{name: 'attr_id'},
					{name: 'attr_name'},
					{name: 'label_text'},
					{name: 'sort_order'},
					{name: 'data_type_id'},
					{name: 'data_type'}
				])
			});
			
			this.store.load();
			
			UsedAttrsList.superclass.constructor.call(this, {
				id: 'usedAttrsList',
				region: 'center',
				title: "元素列表",
				split: true,
				stripeRows: true,
				loadMask: true,
				border: false,
				autoScroll: false,
				cls: 'x-rb',
				viewConfig: {forceFit: true},
				ds: this.store,
				sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
				cm: this.cm
			});
			
			this.getSelectionModel().on('rowselect', function(sm, rowIndex, record) {
				
			});
			
			this.on('rowdblclick', function(grid, rowIdx, e) {
				var record = grid.getSelectionModel().getSelected();
				if(Ext.isEmpty(record))
				{
					Ext.Msg.alert("提示：","系统异常.");
				}else{
					Ext.fly("ref_attr_id").dom.value = record.get("attr_id");
					
					var gp_templateList = Ext.getCmp("gp_templateList");
					var r = gp_templateList.getSelectionModel().getSelected();
					
					Ext.fly("reference_attr").dom.value = r.get("tmplName") + " >> " + record.get("label_text");
					
					Ext.getCmp("win_AttributeRef").hide();
				}
			});
		},
		load: function(){
			this.store.load();
		},
		reload: function(c){
			this.condition.tmpl_id = c;
			this.store.load();
		}
	});	